<?php

namespace App\Http\Controllers\Home;

use App\Http\Controllers\Controller;
use App\Model\Admin\CategoriesModel;
use App\Model\Admin\ProductModel;
use Illuminate\Http\Request;

class ProductsController extends Controller
{
    //
    /**
     * 产品列表
     *
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index()
    {
        $data['categories'] = CategoriesModel::where('pid',1)->get();
        $product_list = ProductModel::where('is_show',1)->get();
        $data['product_list'] = $this->getTree($data['categories'], $product_list);

        return view('front.product-list')->with('data',$data);
    }

    /**
     * 根据分类返回产品列表
     *
     * @param $categories
     * @param $data
     * @return array
     */
    public function getTree($categories,$data)
    {
        $tree = [];
        foreach ($categories as $v){
            $temp = [];
            foreach ($data as $vv){
                if ($v->id == $vv->category_id){
                    $temp[] = $vv;
                }
            }
            $tree[] = $temp;
        }
        return $tree;
    }


    /**
     * 详情
     *
     * @param $url
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function detail($url)
    {
        $Product = new ProductModel();
        $data['info'] = $Product -> where('url',$url)
            ->first();
        $data['products'] = $Product -> where('is_show',1)
            ->orderBy('order')
            ->select(['url','product_name'])
            ->get();
        $data['info']->prooduct_banner = explode(',',$data['info']->product_banner);
        return view('front.product-detail')->with('data',$data);
    }
}
